package com.blank.shop.security.controller;

import com.blank.shop.security.config.BlankShopProperties;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * <br/>Date 2021/9/9
 * <br/>Time 22:59:51
 *
 * @author _blank
 */
@Slf4j
@RestController
public class BrowserSecurityController {

    private final RequestCache requestCache = new HttpSessionRequestCache();

    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Resource
    private HttpServletRequest httpServletRequest;
    @Resource
    private HttpServletResponse httpServletResponse;
    private final BlankShopProperties blankShopProperties;

    public BrowserSecurityController(BlankShopProperties blankShopProperties) {
        this.blankShopProperties = blankShopProperties;
    }

    //    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    @GetMapping(path = {"/authentication/require"})
    public ResponseEntity<Object> requireAuthentication() throws IOException {
        final SavedRequest savedRequest = this.requestCache.getRequest(this.httpServletRequest, this.httpServletResponse);

        if (Objects.nonNull(savedRequest)) {
            final String redirectUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求是：{}", redirectUrl);
            if (StringUtils.endsWithIgnoreCase(redirectUrl, ".html")) {
                final String url = this.blankShopProperties.getBrowser().getLoginPage();
                this.redirectStrategy.sendRedirect(this.httpServletRequest, this.httpServletResponse, url);
            }
        }

        final ImmutableMap<String, String> content = ImmutableMap.of("content", "访问的服务需要身份认证，请引导用户到登录页");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(content);
    }

    @GetMapping(path = {"/session/invalid"})
    public ResponseEntity<Object> sessionInvalid(){
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("session失效");
    }

}
